import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken, setTokenTime } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router/index'
export default {
  namespaced: true,
  state: {
    token: getToken(), // 获取token值
    userInfo: {}, // 用户详细资料
    menu: [],
    point: {
      pDelete: 'point-user-delete',
      pAdd: 'POINT-USER-ADD',
      pUpdate: 'POINT-USER-UPDATE'
    }
  },
  mutations: {
    // 修改添加state里token方法
    setToken(state, payload) {
      state.token = payload
      // 存入本地token
      setToken(payload)
    },
    // 存用户信息
    setUserInfo(state, payload) {
      // console.log(payload)
      state.userInfo = payload
    },
    // 清空删除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 清空用户
    removeUserInfo(state) {
      state.userInfo = {}
    },
    // 用户退出
    logout() {
      this.commit('user/removeToken')
      this.commit('user/removeUserInfo')
      resetRouter()
    },
    // 动态生成侧边栏列表方法
    setMenus(state, payload) {
      state.menu = [...constantRoutes, ...payload]
    }
  },
  actions: {
    // 发起获取登录请求方法
    async  login(context, data) {
      // console.log('发起请求')
      const res = await login(data)
      // 调用修改token方法，存入token数据
      context.commit('setToken', res)
      // 存入登录当时的时间戳
      setTokenTime()
      console.log(res)
    },
    // 获取用户资料的方法请求
    async  getUserInfo(context) {
      // 获取用户一般信息
      const resUser = await getUserInfo()
      // console.log(resUser)
      const id = resUser.userId
      // 获取用户的详细信息
      const userInfo = await getUserDetailById(id)
      // console.log(userInfo)
      context.commit('setUserInfo', { ...resUser, ...userInfo })
      return resUser
    }
  }
}

